package com.hadwinling.service.impl;

import cn.hutool.core.io.file.FileReader;
import com.hadwinling.entity.Burn;
import com.hadwinling.entity.NuclearParam;
import com.hadwinling.mapper.BurnMapper;
import com.hadwinling.mapper.ShikeTimeMapper;
import com.hadwinling.service.RealTimeService;
import org.apache.iotdb.rpc.IoTDBConnectionException;
import org.apache.iotdb.rpc.StatementExecutionException;
import org.apache.iotdb.session.Session;
import org.apache.iotdb.session.SessionDataSet;
import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
import org.apache.iotdb.tsfile.read.common.Field;
import org.apache.iotdb.tsfile.read.common.RowRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Classname RealTimeServiceImpl 实时数据业务
 * @Description TODO
 * @Date 2021/7/9 14:49
 * @Created by
 */
@Service
public class RealTimeServiceImpl implements RealTimeService {
    @Autowired
    private Session iotdbSession;
    @Autowired
    private BurnMapper burnMapper;
    @Autowired
    private ShikeTimeMapper shikeTimeMapper;

    /**
     * 暂不用
     *
     * @param storage    要插入到的存储组
     * @param zujianNum  组件数量
     * @param zhibiaoNum 指标数量
     * @throws StatementExecutionException
     * @throws IoTDBConnectionException
     */
    @Override
    public void realTimeInsertion(String storage, int zujianNum, int zhibiaoNum) throws StatementExecutionException, IoTDBConnectionException {
        FileReader fileReader = new FileReader("D:\\MySoftWare\\PCWare\\Tencent\\AppCache\\WetChatCache\\WeChat Files\\wxid_ysw3yj1tpdwp22\\FileStorage\\File\\2021-06\\go30");
//        FileReader fileReader = new FileReader("/home/hedian/go30");

        List<String> lines = fileReader.readLines();
        int line = 0;
        long timestamp = System.currentTimeMillis();

        String[] shujukuaiArray = {"gl", "kq", "rq", "s", "d", "wd"}; //gl:功率 kq：快群 rq：热群 s: 氙 d: 碘 wd：温度

        List<String> deviceIds = new ArrayList<>();
        List<List<String>> measurementsList = new ArrayList<>();
        List<List<Object>> valuesList = new ArrayList<>();
        List<Long> timestamps = new ArrayList<>();
        List<List<TSDataType>> typesList = new ArrayList<>();

        List<String> measurements = new ArrayList<>();
        List<TSDataType> types = new ArrayList<>();
        for (int i = 0; i < 32; i++) {
            measurements.add("s" + (i + 1));
            types.add(TSDataType.FLOAT);
        }

        for (int zb = 0; zb < zhibiaoNum; zb++) {// 6 个指标

            for (int zj = 0; zj < zujianNum; zj++) { // 52 个组件-

                String deviceId = storage + "." + shujukuaiArray[zb] + ".zj" + zj;
                List<Object> values = new ArrayList<>();
                final String[] s = lines.get(line).split(" ");
                for (int i = 0; i < 32; i++) {
                    String value = s[i];
                    values.add(Float.parseFloat(value));
                }
                line++;
                deviceIds.add(deviceId);
                valuesList.add(values);
                measurementsList.add(measurements);
                typesList.add(types);
                timestamps.add(timestamp);
            }
            try {
                iotdbSession.insertRecords(deviceIds, timestamps, measurementsList, typesList, valuesList);
            } catch (IoTDBConnectionException e) {
                e.printStackTrace();
            } catch (StatementExecutionException e) {
                e.printStackTrace();
            }

            deviceIds.clear();
            measurementsList.clear();
            valuesList.clear();
            timestamps.clear();

        }
    }

    /**
     * 暂不用
     *
     * @param storage
     */
    @Override
    public void realTimeInsertionWithSchedule(String storage) {
//        FileReader fileReader = new FileReader("D:\\MySoftWare\\PCWare\\Tencent\\AppCache\\WetChatCache\\WeChat Files\\wxid_ysw3yj1tpdwp22\\FileStorage\\File\\2021-06\\go30");
        FileReader fileReader = new FileReader("/home/hedian/go30");

        List<String> lines = fileReader.readLines();
        int line = 0;
        long timestamp = System.currentTimeMillis();

        String[] shujukuaiArray = {"gl", "kq", "rq", "s", "d", "wd"}; //gl:功率 kq：快群 rq：热群 s: 氙 d: 碘 wd：温度

        List<String> deviceIds = new ArrayList<>();
        List<List<String>> measurementsList = new ArrayList<>();
        List<List<Object>> valuesList = new ArrayList<>();
        List<Long> timestamps = new ArrayList<>();
        List<List<TSDataType>> typesList = new ArrayList<>();

        List<String> measurements = new ArrayList<>();
        List<TSDataType> types = new ArrayList<>();
        for (int i = 0; i < 32; i++) {
            measurements.add("s" + (i + 1));
            types.add(TSDataType.FLOAT);
        }

        for (int rhb = 0; rhb < 18; rhb++) {

            for (int shike = 0; shike < 98; shike++) { // 98 个时刻

                for (int zb = 0; zb < 6; zb++) {// 6 个指标

                    for (int zj = 0; zj < 52; zj++) { // 52 个组件-

                        String deviceId = storage + shujukuaiArray[zb] + ".zj" + zj;
                        List<Object> values = new ArrayList<>();
                        final String[] s = lines.get(line).split(" ");
                        for (int i = 0; i < 32; i++) {
                            String value = s[i];
                            values.add(Float.parseFloat(value));
                        }
                        line++;
                        deviceIds.add(deviceId);
                        valuesList.add(values);
                        measurementsList.add(measurements);
                        typesList.add(types);
                        timestamps.add(timestamp);
                    }
                    try {
                        iotdbSession.insertRecords(deviceIds, timestamps, measurementsList, typesList, valuesList);
                    } catch (IoTDBConnectionException e) {
                        e.printStackTrace();
                    } catch (StatementExecutionException e) {
                        e.printStackTrace();
                    }

                    deviceIds.clear();
                    measurementsList.clear();
                    valuesList.clear();
                    timestamps.clear();
                }

                timestamp = timestamp + 1000; // 1秒一个时刻
            }
        }
    }

    /**
     * 暂不用
     *
     * @param storage
     */
    @Override
    public void realTimeInsertionWithSleep(String storage) throws InterruptedException {
//        FileReader fileReader = new FileReader("D:\\MySoftWare\\PCWare\\Tencent\\AppCache\\WetChatCache\\WeChat Files\\wxid_ysw3yj1tpdwp22\\FileStorage\\File\\2021-06\\go30");
        FileReader fileReader = new FileReader("/home/hedian/go30");

        List<String> lines = fileReader.readLines();
        int line = 0;
        long timestamp = System.currentTimeMillis();

        String[] shujukuaiArray = {"gl", "kq", "rq", "s", "d", "wd"}; //gl:功率 kq：快群 rq：热群 s: 氙 d: 碘 wd：温度

        List<String> deviceIds = new ArrayList<>();
        List<List<String>> measurementsList = new ArrayList<>();
        List<List<Object>> valuesList = new ArrayList<>();
        List<Long> timestamps = new ArrayList<>();
        List<List<TSDataType>> typesList = new ArrayList<>();

        List<String> measurements = new ArrayList<>();
        List<TSDataType> types = new ArrayList<>();
        for (int i = 0; i < 32; i++) {
            measurements.add("s" + (i + 1));
            types.add(TSDataType.FLOAT);
        }
        while (true) {

            for (int rhb = 0; rhb < 18; rhb++) {

                for (int shike = 0; shike < 98; shike++) { // 98 个时刻

                    for (int zb = 0; zb < 6; zb++) {// 6 个指标

                        for (int zj = 0; zj < 52; zj++) { // 52 个组件-

                            String deviceId = storage + "." + shujukuaiArray[zb] + ".zj" + zj;

                            List<Object> values = new ArrayList<>();
                            final String[] s = lines.get(line).split(" ");
                            for (int i = 0; i < 32; i++) {
                                String value = s[i];
                                values.add(Float.parseFloat(value));
                            }
                            line++;
                            deviceIds.add(deviceId);
                            valuesList.add(values);
                            measurementsList.add(measurements);
                            typesList.add(types);
                            timestamps.add(timestamp);
                        }
                        try {
                            iotdbSession.insertRecords(deviceIds, timestamps, measurementsList, typesList, valuesList);
                        } catch (IoTDBConnectionException e) {
                            e.printStackTrace();
                        } catch (StatementExecutionException e) {
                            e.printStackTrace();
                        }

                        deviceIds.clear();
                        measurementsList.clear();
                        valuesList.clear();
                        timestamps.clear();

                        Thread.sleep(5000); // 睡眠10秒
                        timestamp = timestamp + 1000; // 1秒一个时刻
                    }


                }
            }
        }
    }


    /**
     * 1 .燃耗步 物理场 时间 4D
     *
     * @param nuclearParam 指标
     * @return 组件 和层
     * @throws StatementExecutionException
     * @throws IoTDBConnectionException
     */
    @Override
    public ArrayList<RowRecord> selectTheLastestTimeWithIndicatorReturnModule(NuclearParam nuclearParam) throws StatementExecutionException, IoTDBConnectionException {
        String[] shujukuaiArray = {"gl", "kq", "rq", "s", "d", "wd"}; //gl:功率 kq：快群 rq：热群 s: 氙 d: 碘 wd：温度

        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 32; i++) {
            stringBuffer.append("s" + i + ", ");
            if (i == 31) {
                stringBuffer.append("s" + (i + 1) + " ");
            }
        }
        final ArrayList<RowRecord> lists = new ArrayList<>();
        for (int i = 0; i < 52; i++) {
//            System.out.println("select last " + stringBuffer.toString() + " from root.dc_dx2." + shujukuaiArray[nuclearParam.getIndicator() - 1] + " . zj" + i);
            final SessionDataSet sessionDataSet = iotdbSession.executeQueryStatement("select last " + stringBuffer.toString() + " from root.dc_dx2." + shujukuaiArray[nuclearParam.getIndicator() - 1] + " . zj" + i);
            while (sessionDataSet.hasNext()) {
                final RowRecord next = sessionDataSet.next();
                System.out.println(next);
                lists.add(next);
            }
        }
        return lists;
    }

    /**
     * 查找最近第几个 数据
     *
     * @param nuclearParam 指标
     * @return
     */
    @Override
    public ArrayList<RowRecord> selectTheLastestNoTimeWithIndicatorReturnModule(NuclearParam nuclearParam) throws StatementExecutionException, IoTDBConnectionException {
        String[] shujukuaiArray = {"gl", "kq", "rq", "s", "d", "wd"}; //gl:功率 kq：快群 rq：热群 s: 氙 d: 碘 wd：温度

        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 32; i++) {
            stringBuffer.append("s" + i + ", ");
            if (i == 31) {
                stringBuffer.append("s" + (i + 1) + " ");
            }
        }

        final ArrayList<RowRecord> rowRecords = new ArrayList<>();
        for (int i = 0; i < 52; i++) {
//            System.out.println("select " + stringBuffer.toString() + " from root.dc_dx2." + shujukuaiArray[nuclearParam.getIndicator() - 1] + ".zj" + i + " order by time desc limit " + nuclearParam.getTime_end());
            final SessionDataSet sessionDataSet = iotdbSession.executeQueryStatement("select " + stringBuffer.toString() + " from root.dc_dx2." + shujukuaiArray[nuclearParam.getIndicator() - 1] + ".zj" + i + " order by time desc limit " + nuclearParam.getTime_end());
            while (sessionDataSet.hasNext()) {
                final RowRecord next = sessionDataSet.next();
//                System.out.println(next);
                rowRecords.add(next);
            }
            System.out.println();

        }
        return rowRecords;
    }


    /**
     * 2.燃耗步 物理场 时间
     *
     * @param nuclearParam
     * @return 返回 层 和 组件
     * @throws StatementExecutionException
     * @throws IoTDBConnectionException
     */
    @Override
    public ArrayList<List<Field>> selectTheLatestTimeWithReturnLayerAndModule(NuclearParam nuclearParam) throws StatementExecutionException, IoTDBConnectionException {
        String[] shujukuaiArray = {"gl", "kq", "rq", "s", "d", "wd"}; //gl:功率 kq：快群 rq：热群 s: 氙 d: 碘 wd：温度

        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 32; i++) {
            stringBuffer.append("s" + i + ", ");
            if (i == 31) {
                stringBuffer.append("s" + (i + 1) + " ");
            }
        }
        final ArrayList<List<Field>> lists = new ArrayList<>();
        for (int i = 0; i < 52; i++) {
            final SessionDataSet sessionDataSet = iotdbSession.executeQueryStatement("select last " + stringBuffer.toString() + " from root.dc_dx2." + shujukuaiArray[nuclearParam.getIndicator() - 1] + " . zj" + i);
            while (sessionDataSet.hasNext()) {
                final RowRecord next = sessionDataSet.next();
                final List<Field> fields = next.getFields();
                lists.add(fields);
            }
        }

        return lists;
    }

    /**
     * 3 .燃耗步 物理场 组件 有问题， 没考虑跨燃耗步
     *
     * @param nuclearParam 指标
     * @return 层 和时刻
     */
    @Override
    public ArrayList<List<Field>> selectTheLatestTimeWithReturnLayerAndTime(NuclearParam nuclearParam) throws StatementExecutionException, IoTDBConnectionException {
        String[] shujukuaiArray = {"gl", "kq", "rq", "s", "d", "wd"}; //gl:功率 kq：快群 rq：热群 s: 氙 d: 碘 wd：温度
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 32; i++) {
            stringBuffer.append("s" + i + ", ");
            if (i == 31) {
                stringBuffer.append("s" + (i + 1) + " ");
            }
        }
        final ArrayList<List<Field>> lists = new ArrayList<>();
        final SessionDataSet sessionDataSet = iotdbSession.executeQueryStatement("select last " + stringBuffer.toString() + " from root.dc_dx2." + shujukuaiArray[nuclearParam.getIndicator() - 1] + " . zj" + (nuclearParam.getModule() - 1) + " order by time desc limit " + nuclearParam.getTime_end());
        while (sessionDataSet.hasNext()) {
            final RowRecord next = sessionDataSet.next();
            final List<Field> fields = next.getFields();
            System.out.println(fields);
            lists.add(fields);
        }


        return lists;
    }

    /**
     * 4 时刻 组件 物理场(
     *
     * @param nuclearParam 物理场 组件
     * @return 层 和 燃耗步
     * @throws StatementExecutionException
     * @throws IoTDBConnectionException
     */
    @Override
    public ArrayList<List<Field>> selectTheLatestTimeWithReturnLayerAndBurn(NuclearParam nuclearParam) throws StatementExecutionException, IoTDBConnectionException {
        String[] shujukuaiArray = {"gl", "kq", "rq", "s", "d", "wd"}; //gl:功率 kq：快群 rq：热群 s: 氙 d: 碘 wd：温度
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 32; i++) {
            stringBuffer.append("s" + i + ", ");
            if (i == 31) {
                stringBuffer.append("s" + (i + 1) + " ");
            }
        }
        ArrayList<List<Field>> arrayLists = new ArrayList<>();
        final SessionDataSet sessionDataSet = iotdbSession.executeQueryStatement("select last " + stringBuffer.toString() + " from root.dc_dx2." + shujukuaiArray[nuclearParam.getIndicator() - 1] + " . zj" + (nuclearParam.getModule() - 1));
        while (sessionDataSet.hasNext()) {
            final List<Field> fields = sessionDataSet.next().getFields();
            System.out.println(fields);
            arrayLists.add(fields);
        }
        return arrayLists;

    }

    /**
     * 6. 组件 层 物理场2d
     *
     * @param nuclearParam 物理场， 时刻
     * @return
     */
    @Override
    public ArrayList<List<Field>> select_Module_layer_Indicator_With_Return_time(NuclearParam nuclearParam) throws StatementExecutionException, IoTDBConnectionException {
        String[] shujukuaiArray = {"gl", "kq", "rq", "s", "d", "wd"}; //gl:功率 kq：快群 rq：热群 s: 氙 d: 碘 wd：温度

        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 32; i++) {
            stringBuffer.append("s" + i + ", ");
            if (i == 31) {
                stringBuffer.append("s" + (i + 1) + " ");
            }
        }
        ArrayList<List<Field>> arrayLists = new ArrayList<>();
        final SessionDataSet sessionDataSet = iotdbSession.executeQueryStatement("select " + stringBuffer.toString() + " from root.dc_dx2." + shujukuaiArray[nuclearParam.getIndicator() - 1] + ".zj" + (nuclearParam.getModule() - 1) + "order by time desc limit " + nuclearParam.getTime_end());
        while (sessionDataSet.hasNext()) {
            final RowRecord next = sessionDataSet.next();
            final List<Field> fields = next.getFields();
            arrayLists.add(fields);
        }
        return arrayLists;


    }

    /**
     * 2.1 plot_burn_indicator_module_real_time (burn,indicator,module,time_end)
     *
     * @param nuclearParam 传过来的值
     * @return
     */
    @Override
    public ArrayList<List<Field>> plot_burn_indicator_module_real_time(NuclearParam nuclearParam) throws StatementExecutionException, IoTDBConnectionException {
        final List<Burn> burns = burnMapper.selectAllByBurnidBetweenBurnid(nuclearParam.getBurn_start(), nuclearParam.getBurn_end());
        String burn_Start_time = burns.get(0).getStart();
        String burn_end_time = burns.get(burns.size() - 1).getEnd();

        String[] shujukuaiArray = {"gl", "kq", "rq", "s", "d", "wd"}; //gl:功率 kq：快群 rq：热群 s: 氙 d: 碘 wd：温度

        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 32; i++) {
            stringBuffer.append("s" + i + ", ");
            if (i == 31) {
                stringBuffer.append("s" + (i + 1) + " ");
            }
        }
        ArrayList<List<Field>> arrayLists = new ArrayList<>();
//        System.out.println("select " + stringBuffer.toString() + "from root.dc_dx2." + shujukuaiArray[nuclearParam.getIndicator() - 1] +
//                ".zj" + (nuclearParam.getModule() - 1) + " where time >= " + burn_Start_time + " and time < " + burn_end_time + " order by time desc limit " + nuclearParam.getTime_end());
        final SessionDataSet sessionDataSet = iotdbSession.executeQueryStatement("select " + stringBuffer.toString() + "from root.dc_dx2." + shujukuaiArray[nuclearParam.getIndicator() - 1] +
                ".zj" + (nuclearParam.getModule() - 1) + " where time >= " + burn_Start_time + " and time < " + burn_end_time + " order by time desc limit " + nuclearParam.getTime_end());
        while (sessionDataSet.hasNext()) {
            final RowRecord next = sessionDataSet.next();
            final List<Field> fields = next.getFields();
            arrayLists.add(fields);
        }
        return arrayLists;
    }


}
